<template>
    <div class="new-page" :style="`min-height: ${pageMinHeight}px`">
        <div class="table_box">
            <div class="table_header">
                    <selectObj @change="handleChange"></selectObj>
                    <!-- <a-input-search placeholder="运维人员/运维对象/运维内容" style="width: 250px" v-model="searchData.name" @search="onSearch" /> -->
            </div>
            <div class="realTime_box" v-if="e_s_cluster_id">
                <div class="realTime_title">
                    <span class="icon iconfont icon-shishishuju-shishigongkuang"></span>
                    <span class="desc">实时工况</span>
                </div>
                <a-table :columns="columns" :rowKey="(record) => record.id" :data-source="realtime_data" :pagination="false"
                    @change="handleTableChange">
                </a-table>
            </div>
            <div class="realTime_box" v-if="e_s_cluster_id">
                <div class="realTime_title">
                    <span class="icon iconfont icon-shishishuju-chongfangdianliang"></span>
                    <span class="desc">充放电量</span>
                    <span class="btn" @click="openRecordList">充放电记录</span>
                </div>
                <a-table :columns="columns2" :rowKey="(record) => record.id" :data-source="[data.power_info]" :pagination="false"
                    @change="handleTableChange">
                </a-table>
            </div>
            <div class="realTime_box" v-if="e_s_cluster_id">
                <div class="realTime_title">
                    <span class="icon iconfont icon-dianchiculisanfenxi"></span>
                    <span class="desc">电池簇信息</span>
                </div>
                <a-table :columns="columns3" :rowKey="(record) => record.id" :data-source="[data.clusters_info]" :pagination="false"
                    @change="handleTableChange">
                </a-table>
            </div>
            <div class="realTime_box" v-else>
                <div id="" style="padding: 100px 0;color: #999;">
                    请先选择站点单元簇
                </div>
            </div>
            <div class="" style="display: flex;" v-if="e_s_cluster_id">
                <div class="realTime_box" style="flex: 1;margin-right: 10px;">
                    <div class="realTime_title">
                        <span class="icon iconfont icon-shishishuju-gongshuaisoc"></span>
                        <span class="desc">实时功率及SOC曲线</span>
                    </div>
                    <div class="charts_trend">
                        <div id="charts_trend" style="width: 80%; height: 300px"></div>
                    </div>
                </div>
                <div class="realTime_box" style="flex: 1;margin-left: 10px;">
                    <div class="realTime_title">
                        <span class="icon iconfont icon-shishishuju-shishigaojing"></span>
                        <span class="desc">实时告警</span>
                    </div>
                    <div class="status_box">
                        <div class="status">
                            <div class="">
                                <span class="icon c1"></span>
                                <span class="desc">重度</span>
                            </div>
                            <div class="">
                                <span class="icon c2"></span>
                                <span class="desc">中度</span>
                            </div>
                            <div class="">
                                <span class="icon c3"></span>
                                <span class="desc">轻度</span>
                            </div>
                            <div class="">
                                <span class="icon c4"></span>
                                <span class="desc">正常</span>
                            </div>
                        </div>
                        <div class="status_btn">
                            <span class="btn" :class="{active:status==1}" @click="status=1">告警看板</span>
                            <span class="btn" :class="{active:status==2}" @click="status=2">告警列表</span>
                        </div>
                    </div>
                    <div class="bulletinBoard" v-if="status==1">
                        <div v-for="res,i in alarm_box" :key="i" :class="res.class">
                            <span v-for="ress,ii in res.data" @click="showTempAlarm(ress)" :class="ress.class || ''" :key="ii">{{ress.name}}{{ress.num?`(${ress.num})`:''}}</span>
                        </div>
                        
                    </div>
                    <div class="table_lsit" v-if="status==2">
                        <a-table :columns="columns4" :rowKey="(record) => record.id" :data-source="data.alarm_detail" :pagination="false"
                            @change="handleTableChange">
                            <div slot="level" slot-scope="text, record">
                              <div :class="level[record.level].c">
                                  <span class="iconfont icon-dianchijingbao"></span>
                                  <span style="margin-left: 5px;">{{level[record.level].n}}</span>
                              </div>
                            </div>
                        </a-table>
                    </div>
                </div>
            </div>
            
            
            <a-modal v-model="visible" title="充放电记录" on-ok="handleOk" width="60%">
                <template slot="footer">
                    <a-button key="back" @click="visible=false">
                        关闭
                    </a-button>
                </template>
                <div class="form_box">
                    <a-table :columns="columns5" :rowKey="(record) => record.id" :data-source="data.power_detail " :pagination="false"
                      @change="handleTableChange">
                       <div slot="state" slot-scope="text, record">
                           {{level[record.state].n}}
                       </div>
                       <div slot="time" slot-scope="text, record">
                           {{getTime(record)}}
                       </div>
                       <div slot="power" slot-scope="text, record">
                           {{record.power}}Kwh
                       </div>
                       
                    </a-table>
                </div>
            </a-modal>
            <a-modal v-model="visible2" title="告警列表" on-ok="handleOk" width="60%">
                <template slot="footer">
                    <a-button key="back" @click="visible2=false">
                        关闭
                    </a-button>
                </template>
                <div class="form_box">
                    <a-table :columns="columns4" :rowKey="(record) => record.id" :data-source="tempAlarms" :pagination="false"
                        @change="handleTableChange">
                        <div slot="level" slot-scope="text, record">
                          <div :class="level[record.level].c">
                              <span class="iconfont icon-dianchijingbao"></span>
                              <span style="margin-left: 5px;">{{level[record.level].n}}</span>
                          </div>
                        </div>
                    </a-table>
                </div>
            </a-modal>
        </div>
    </div>
</template>

<script>
    import {
        mapState
    } from "vuex";
    import {
        gets,
        del
    } from "@/services";
    import {
        getSearchCriteria
    } from "@/utils/util"
    import selectObj from "@/components/selectObj/selectObj"
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows);
      },
    };
    export default {
        components: {
            selectObj
        },
        data() {
            return {
                alarm_box:[
                    {
                        class:'row4',
                        data:[
                            {name:'簇电压欠压',num:0},
                            {name:'过流',num:0},
                            {name:'漏电',num:0},
                            {name:'单体高温',num:0},
                        ]
                    },
                    {
                        class:'row4',
                        data:[
                            {name:'模组温差过大',num:0},
                            {name:'与BCMU通讯故障',num:0},
                            {name:'自身故障',num:0},
                            {name:'与PCS通讯故障',num:0},
                        ]
                    },
                    {
                        class:'row5',
                        data:[
                            {name:'簇电压过压',num:0},
                            {name:'单体欠压',num:0},
                            {name:'单体低温',num:0},
                            {name:'单体过压',num:0},
                            {name:'内短路',num:0},
                        ]
                    },
                ],
                columns: [
                    {title: "功率",dataIndex: "power",key: "power",className:'column-white'},
                    {title: "电压",key: "voltage",dataIndex: "voltage",className:'column-white'},
                    {title: "电流",key: "current",dataIndex: "current",className:'column-white'},
                    {title: "当前温度",key: "temperature",dataIndex: "temperature",className:'column-white'},
                    {title: "SOC",key: "SOC",dataIndex: "SOC",className:'column-white'},
                    {title: "SOH",key: "SOH",dataIndex: "SOH",className:'column-white'},
                    {title: "最大温度",key: "max_temperature",dataIndex: "max_temperature",className:'column-white'},
                    {title: "最小温度",key: "min_temperature",dataIndex: "min_temperature",className:'column-white'},
                    {title: "最大电压",key: "max_voltage",dataIndex: "max_voltage",className:'column-white'},
                    {title: "最小电压",key: "min_voltage",dataIndex: "min_voltage",className:'column-white'}
                    
                ],
                columns2:[
                    {title: "可充电量",dataIndex: "available_in",key: "available_in",className:'column-white'},
                    {title: "可放电量",dataIndex: "available_out",key: "available_out",className:'column-white'},
                    {title: "今日充电量",dataIndex: "today_charge",key: "today_charge",className:'column-white'},
                    {title: "今日放电量",dataIndex: "today_discharge",key: "today_discharge",className:'column-white'},
                    {title: "累计充电量",dataIndex: "total_charge",key: "total_charge",className:'column-white'},
                    {title: "累计放电量",dataIndex: "total_discharge",key: "total_discharge",className:'column-white'},
                    {title: "自然放电率",dataIndex: "natural_discharge_rate",key: "natural_discharge_rate",className:'column-white'},
                    {title: "充放电量极差",dataIndex: "Charge_discharge_energy_maxdiff",key: "Charge_discharge_energy_maxdiff",className:'column-white'},
                ],
                columns3:[
                    {title: "电池簇",dataIndex: "location",key: "location",className:'column-white'},
                    {title: "电压",dataIndex: "capacity",key: "capacity",className:'column-white'},
                    {title: "电流",dataIndex: "current_power",key: "current_power",className:'column-white'},
                    {title: "SOC",dataIndex: "name4",key: "name4",className:'column-white'},
                    {title: "SOH",dataIndex: "name5",key: "name5",className:'column-white'},
                    {title: "最大电芯温度",dataIndex: "name6",key: "name6",className:'column-white'},
                    {title: "最小电芯温度",dataIndex: "name6",key: "name6",className:'column-white'},
                    {title: "最大电芯电压",dataIndex: "name6",key: "name6",className:'column-white'},
                    {title: "最小电芯电压",dataIndex: "name6",key: "name6",className:'column-white'},
                ],
                columns4:[
                    {title: "告警名称",dataIndex: "name",key: "name",className:'column-white'},
                    {title: "告警时间",dataIndex: "created_at",key: "created_at",className:'column-white'},
                    {title: "持续时长",dataIndex: "name3",key: "name3",className:'column-white'},
                    {title: "定位",dataIndex: "type",key: "type",className:'column-white'},
                    {title: "告警等级",dataIndex: "level",className:'column-white',scopedSlots: {customRender: "level"}}
                ],
                columns5:[
                    {title: "电池簇",dataIndex: "e_s_cluster_id",key: "e_s_cluster_id"},
                    {title: "类型",dataIndex: "state",scopedSlots: { customRender: "state" }},
                    {title: "开始时间",dataIndex: "begin_at",key: "begin_at"},
                    {title: "持续时长",dataIndex: "time",scopedSlots: { customRender: "time" }},
                    {title: "累计电量",dataIndex: "power",scopedSlots: { customRender: "power" }}
                ],
                level:{
                    charge:{
                        n:'充电'
                    },
                    discharge:{
                        n:'放电'
                    }
                },
                visible: false,
                visible2: false,
                status:2,
                rowSelection,
                form: {},
                
                labelCol: {
                    span: 7
                },
                wrapperCol: {
                    span: 11
                },
                rules: {
                    name: [{
                        required: true,
                        message: "请输入角色名称",
                        trigger: "blur",
                    }, ],
                    role_id: [{

                        required: true,
                        message: "请选择角色",
                        trigger: "change",
                    }, ],
                    enterprise_id: [{

                        required: true,
                        message: "请选择企业",
                        trigger: "change",
                    }, ],
                    mobile: [{
                        required: true,
                        message: "请输入账号电话",
                        trigger: "blur",
                    }, ],
                    password: [{
                        required: true,
                        message: "请输入账号密码",
                        trigger: "blur",
                    }, ]
                },
                pagination: {
                    pageSize: 10,
                },
                searchData: {
                    name: ''
                },
                loading: false,
                data: [],
                realtime_data:[],
                e_s_cluster_id:'10',
                level:{
                    normal:{
                        c:'level1',
                        n:'正常'
                    },
                    light:{
                        c:'level2',
                        n:'轻度'
                    },
                    moderate:{
                        c:'level3',
                        n:'中度'
                    },
                    severe:{
                        c:'level4',
                        n:'重度'
                    },
                },
                tempAlarms:[]
            };
        },
        computed: {
            ...mapState("setting", ["pageMinHeight"]),
        },
        created() {
            let id = localStorage.getItem ('e_s_cluster_id');
            if(id){
                this.e_s_cluster_id = id
                this.fetch({
                    e_s_cluster_id: id
                })
            }
        },
        mounted() {
          
        },
        methods: {
            showTempAlarm(e){
                console.log(e);
                if(e.num >0){
                    this.visible2=true
                    this.tempAlarms = this.data.alarm_detail.filter(ee=>e.name==ee.name)
                }
            },
            handleChange(e){
              let id = e[2]
                if(id){
                    this.e_s_cluster_id = id
                    this.fetch({
                        e_s_cluster_id: id
                    })
                }
            },
            getTime(e){
              let time = (new Date(e.end_at).getTime() - new Date(e.begin_at).getTime())/1000
              time= (time/60/24).toFixed(2)
              return `${time}h`
            },
            openRecordList(){
                this.visible= true
            },
            init_nedw_trend(id, data) {
              let time = data.map((e) => e.created_at);
              var legend = ["功率", "SOC"];
              var voltage = data.map((e) => e.SOH);
              var current = data.map((e) => e.power);
            
              let option = {
                //默认色板
                color: ["#dd3ee5", "#12e78c", "#fe8104"],
                //标题，可以自定义标题的位置和样式
                title: {
                  //text: '服务指标'
                },
                //鼠标hover提示框
                tooltip: {
                  trigger: "axis", //触发类型；轴触发，axis则鼠标hover到一条柱状图显示全部数据，item则鼠标hover到折线点显示相应数据，
                  axisPointer: {
                    //坐标轴指示器，坐标轴触发有效，
                    type: "cross", //默认为line，line直线，cross十字准星，shadow阴影
                    crossStyle: {
                      color: "#fff",
                    },
                  },
                },
            
                //图例
                legend: {
                  data: legend, //注意：图例的名字必须跟下面series数组里面的name一致
                  itemHeight: 9, //改变圆圈大小
                  top:15,
                  icon: "circle",
                  textStyle: {
                    color: "#333", // 图例文字颜色
                  },
                },
                xAxis: [
                  {
                    type: "category",
                    data: time,
                    axisLabel: {
                      formatter: function (value, idx) {
                        var date = new Date(value);
                        return idx === 0
                          ? value
                          : [date.getMonth() + 1, date.getDate()].join("-");
                      },
                      margin: 15
                    },
                    axisLine: {
                      lineStyle: {
                        color: "#C3CBD5",
                      },
                    },
                    axisTick: {
                      show: false,
                    },
                    boundaryGap: false,
                  },
                ],
                yAxis: [
                  //第一个Y轴
                  {
                    position: "left",
                    type: "value", //轴类型，横轴默认为类目型'category'，纵轴默认为数值型'value'，
                    name: "功率(KW)",
                    //坐标轴文本样式，nameTextStyle和axisLabel区别是，前者管坐标轴顶端文字（坐标轴标题），或者管轴上断点的文字标签
                    nameTextStyle: {
                      padding: 10, //内边距
                    },
                    //坐标轴文字标签
                    axisLabel: {
                      show: true
                    },
                    //坐标轴线
                    axisLine: {
                      show: true,
                      lineStyle: {
                        color: "#C3CBD5",
                      },
                    },
                    //分割线/网格样式
                    splitLine: {
                      show: true,
                      lineStyle: {
                        width: 1,
                        type: "dotted", //实心，solid | dotted | dashed，
                      },
                    },
                  },
                  //第二个Y轴
                  {
                    position: "right",
                    type: "value",
                    name: "SOC(%)",
                    nameTextStyle: {
                      padding: 10,
                    },
                    axisLabel: {
                      show: true,
                    },
                    axisLine: {
                      show: true,
                      lineStyle: {
                        color: "#C3CBD5",
                      },
                    },
                    //分割线/网格
                    splitLine: {
                      show: true, //是否显示网格
                      lineStyle: {
                        width: 1,
                        type: "dotted",
                      },
                    },
                  },
                ],
                series: [
                  {
                    name: "功率",
                    type: "line", //数据表现形式（bar为柱形图，line为折线图）
                    yAxisIndex: 0, //选择index为1的Y轴作为参考系
                    data: current,
                    //线条样式，如折线图
                    itemStyle: {
                      normal: {
                        color: '#206EF7',
                        barBorderRadius: [10, 10, 10, 10],
                      },
                    },
                  },
                  {
                    name: "SOC",
                    type: "line",
                    yAxisIndex: 1, //选择index为1的Y轴作为参考系
                    data: voltage,
                    itemStyle: {
                      normal: {
                        color: "#F76720",
                        barBorderRadius: [10, 10, 10, 10],
                      },
                    },
                  },
                ],
              };
              var myChart = this.$echarts.init(document.getElementById(id));
              // 使用刚指定的配置项和数据显示图表
              myChart.setOption(option);
              window.addEventListener("resize", function () {
                myChart.resize();
              });
            },
            handleTableChange(pagination, filters) {
                console.log(pagination, filters);
                const pager = {
                    ...this.pagination
                };
                pager.current = pagination.current;
                this.pagination = pager;
                this.fetch({
                    page: pagination.current,
                    limit: pagination.pageSize,
                    ...filters,
                });
            },
            fetch(params = {}) {
                this.loading = true;
                gets({
                  ...params,
                  ...(getSearchCriteria(this.searchData))
                },'realtime').then(({ data }) => {
                  if (data.code == 20000) {
                  
                    this.data = data.data 
                    this.data.power_info.total_discharge+='kWh'
                    this.data.power_info.available_in+='kWh'
                    this.data.power_info.available_out+='kWh'
                    this.data.power_info.today_charge+='kWh'
                    this.data.power_info.today_discharge+='kWh'
                    this.data.power_info.total_charge+='kWh'
                    this.data.power_info.natural_discharge_rate+='%'
                    this.data.power_info.Charge_discharge_energy_maxdiff+='kWh'
                    
                    this.data.clusters_info.capacity+='V'
                    this.data.clusters_info.current_power+='A'

                    let realtime_data =data.data.current_info
                    //加单位
                    realtime_data.power+='Kw'
                    realtime_data.voltage+='V'
                    realtime_data.current+='A'
                    realtime_data.temperature+='℃'
                    realtime_data.min_temperature+='℃'
                    realtime_data.max_temperature+='℃'
                    realtime_data.max_voltage+='V'
                    realtime_data.min_voltage+='V'
                    realtime_data.SOC+='%'
                    realtime_data.SOH+='%'
                    
                    this.realtime_data = [realtime_data]
                    this.init_nedw_trend("charts_trend", data.data.history_info);
                    // let alarm_info = data.data.alarm_info
                    let alarm_detail = data.data.alarm_detail
                    let l = {
                        normal:0,
                        light:1,
                        moderate:2,
                        severe:3
                    }
                    alarm_detail.map(e=>{
                        e.name
                    })
                    this.alarm_box.map((e,i)=>{
                        e.data.map((ee,ii)=>{
                            let num = 0
                            let temp = alarm_detail.filter(e=>e.name == ee.name)
                            temp.map(e=>{
                                num = num<l[e.level]?l[e.level]:num
                            })
                            ee.num = temp.length
                            if(num!=0){
                                ee.class = `c${num}`
                            }
                            
                            // if(ee.name == item){
                            //     ee.num = alarm_info[item]
                            //     if(ee.num>0 && ee.num<6){
                            //         ee.class = 'c3'
                            //     }else if(ee.num>5 && ee.num<10){
                            //         ee.class = 'c2'
                            //     }else if(ee.num>9){
                            //         ee.class = 'c1'
                            //     }
                            // }
                        })
                    })
                    for(let item in alarm_info){
                        this.alarm_box.map((e,i)=>{
                            e.data.map((ee,ii)=>{
                                if(ee.name == item){
                                    ee.num = alarm_info[item]
                                    if(ee.num>0 && ee.num<6){
                                        ee.class = 'c3'
                                    }else if(ee.num>5 && ee.num<10){
                                        ee.class = 'c2'
                                    }else if(ee.num>9){
                                        ee.class = 'c1'
                                    }
                                }
                            })
                        })
                    }
                    this.pagination = {
                            total: 20,
                        };
                    }
                  this.loading = false;
                });
            },
            delData(id) {
                let _this = this
                this.$confirm({
                    title: "是否确定删除这条数据?",
                    content: "数据删除后将无法恢复",
                    okText: "确定",
                    okType: "danger",
                    cancelText: "取消",
                    onOk() {
                        del(id, 'users').then(({
                            data
                        }) => {
                            if (data.code == 20000) {
                                _this.$message.success("删除成功");
                                console.log(_this.pagination);
                                let i = 0;
                                if (_this.data.length == 1) {
                                    i = 1;
                                }
                                _this.fetch({
                                    limit: 10,
                                    page: _this.pagination.current - i
                                });
                            }
                        });
                    },
                    onCancel() {
                        console.log("Cancel");
                    },
                });
            },
            goupdata(id) {
                this.visible = true
                // this.$router.push(`/account/member/updata?id=${id}`);
            },
            goadd() {
                this.$router.push(`/account/member/add`);
            },
            onSearch() {
                this.fetch({
                    limit: 10
                })
            },
        },
    };
</script>

<style scoped lang="less">
    
    .realTime_box{
        margin-top: 10px;
        .realTime_title{
          height: 36px;
          background: #F7F8FA;
          border-radius: 4px 4px 0px 0px;
          text-align: left;
          line-height: 36px;
          display: flex;
          align-items: center;
          font-size: 14px;
          padding-right: 20px;
          .icon{
              display: inline-block;
              width: 20px;
              height: 20px;
              line-height: 20px;
              color: #1890ff;
              text-align: center;
              font-size: 14px;
              border-radius: 50%;
              background-color: #fff;
              border: 1px solid #1890ff;
              margin: 0 10px 0 26px;
          }
          .desc{
              
          }
          .btn{
              margin-left: auto;
              font-family: PingFang SC;
              font-weight: 500;
              color: #206EF7;
              cursor: pointer;
          }
      }  
        .status_box{
            display: flex;
            justify-content: space-between;
            padding: 20px 0;
            .status{
                display: flex;
                align-items: center;
                margin-left: 20px;
                div{
                    margin-right: 20px;
                    .icon{
                        display: inline-block;
                        border: 4px solid #FF2323;
                        border-radius: 2px;
                    }
                    .desc{
                        font-size: 14px;
                        font-family: PingFang SC;
                        font-weight: 400;
                        color: #333333;
                        margin-left: 5px;
                    }
                    .c1{
                       border-color: #FF2323;
                       background-color: #FF2323;
                    }
                    .c2{
                        border-color: #FF6600;
                        background-color: #FF6600;
                    }
                    .c3{
                        border-color: #FFE300;
                        background-color: #FFE300;
                    }
                    .c4{
                        border-color: #02B887;
                        background-color: #02B887;
                    }
                }
            }
            .status_btn{
                background: #FFFFFF;
                border: 1px solid #E6EAF2;
                border-radius: 4px 0px 0px 4px;
                font-size: 14px;
                font-family: PingFang SC;
                font-weight: 400;
                color: #6E7584;
                cursor: pointer;
                .btn{
                    display: inline-block;
                    padding: 9px 16px;
                }
                .btn:nth-of-type(1){
                    border-right: 1px solid #F7F8FA;
                }
                .active{
                    background: #F7F8FA;
                    color: #000000;
                }
            }
        }
        .bulletinBoard{
            .row4,.row5{
                display: flex;
                margin-bottom: 14px;
                gap:16px;
                span{
                    flex: 1;
                    display: inline-block;
                    text-align: center;
                    height: 66px;
                    line-height: 66px;
                    background: #02B887;
                    border-radius: 4px;
                    cursor: pointer;
                }
                .c3{
                   background: #FF2323;
                }
                .c2{
                    background: #FF6600;
                }
                .c1{
                    background: #FFE300;
                }
            }
            
        
        }
    }
    
    
    
    
    .form_box{
        .form{
            display: flex;
            flex-wrap: wrap;
            .item{
                width: 33%;
            }
        }
        .addrecord{
            padding: 20px 0;
        }
    }
    .new-page {
        height: 100%;
        background-color: @base-bg-color;
        text-align: center;
        border-radius: 4px;

        .table_box {
            padding: 16px 23px;

            .table_header {
                display: flex;
                padding-bottom: 24px;
            }
        }
    }
    .level1{
        color:#16E6FF ;
    }
    .level2{
        color: #FFE300;
    }
    .level3{
        color: #FF6600;
    }
    .level4{
        color: #FF2F4F;
    }
</style>
